package coupon;

import models.BaseModel;
import models.constants.DeletedStatus;
import order.Order;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import util.common.UStringUtil;

import javax.persistence.*;
import java.util.List;
import java.util.Map;

/**
 * 抵扣券
 * Created by Yangshancheng
 * on 2017/1/6.
 * Time : 下午12:31
 */
@Entity
@Table(name = "deductible_coupons")
public class DeductibleCoupon extends BaseModel {

    /**
     * 抵扣券类型信息
     */
    @JoinColumn(name = "deductible_coupon_type_id")
    @ManyToOne
    public DeductibleCouponType deductibleCouponType;

    /**
     * 抵扣券编码
     */
    @Column(name = "coupon_code")
    public String couponCode;

    /**
     * 抵扣券 用在哪个订单上
     * 如果订单信息为空 则表明没有被使用
     * 订单信息
     */
    @JoinColumn(name = "order_id")
    @ManyToOne
    public Order order;


    /**
     * 逻辑删除状态
     */
    @Column(name = "deleted")
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted;

    /**
     * 备注
     */
    @Column(name = "remark")
    public String remark;


    /**
     *
     * @param id
     * @return
     */
    public static DeductibleCoupon findByCouponId(long id){
        return DeductibleCoupon.find(" id = ? and deleted = ?", id , DeletedStatus.UN_DELETED).first();
    }

    /**
     * 删除代扣券
     * @param delIds
     */
    public static void deleteDeductibleCoupon(Long[] delIds){
        String idStr = UStringUtil.concatStr(",", delIds);
        String sqlUpdate = "update deductible_coupons a set a.deleted = 1 where a.id in("+idStr+") " ;
        em().createNativeQuery(sqlUpdate).executeUpdate();
    }

    /**
     * 检查添加的卡券是否存在
     * @param couponTypeId
     * @param insertCodes
     * @return
     */
    public static String checkIsExist(long couponTypeId ,String[] insertCodes){
        String codeStr = UStringUtil.concatStr(",",insertCodes);
        String sqlSelect = " select * from deductible_coupons a where  a.deleted = 0 and a.deductible_coupon_type_id = " + couponTypeId + " and a.coupon_code in ("+codeStr+")";
        String codes="";
        Query query = DeductibleCoupon.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String,Object>> resultList = query.getResultList();
        if(resultList.size() > 0){
            for(Map<String,Object>  map : resultList){
                codes += map.get("coupon_code") + ",";
            }
        }

        return codes;

    }


}
